import React, { useRef, useState, useEffect } from 'react';
import styles from './index.module.less';
import DocTotal from '../components/doc-content';
import { Toast } from 'antd-mobile-v2';
import { PublishDoc, SaveDoc, PublishEditDoc, SaveEditDoc } from '@/services/official-doc';
// import { GetOrgTree } from '@/services/index';
import { DocDetail } from '@/pages/official-doc/interface';
import { Prompt } from 'react-router-dom';
import { clearRouteBlocker, setRouteBlocker } from '@/components/form-group/route-blocker';
import { getSearchName } from '@/utils';

const DocCreatePage: React.FC<RouterProps> = (props) => {
  const id = useRef(props.match?.params?.id);
  const [loading, setLoading] = useState<{ publish: boolean; save: boolean }>({ publish: false, save: false });

  useEffect(() => {
    if (Object.values(loading).indexOf(true) > -1) {
      setTimeout(() => {
        setLoading({ publish: false, save: false });
      }, 30000);
    }
  }, [loading]);

  const handlePublish = async (data: DocDetail) => {
    if (loading.publish) return;
    setLoading({ ...loading, publish: true });
    let AjaxRequest;
    if (id.current) {
      AjaxRequest = PublishEditDoc;
    } else {
      AjaxRequest = PublishDoc;
    }
    const res = await AjaxRequest(data);
    if (res.status === 200) {
      clearRouteBlocker();
      Toast.success('发布成功');
      const entryFromUrl = getSearchName('entry');
      if (entryFromUrl === 'draft') {
        // 草稿页跳转过来时，跳转回去
        return props.history.goBack();
      }
      props.history.replace('/official-doc/2');
    }
    setLoading({ ...loading, publish: false });
  };

  const handleSave = async (data: DocDetail) => {
    if (loading.save) return;
    setLoading({ ...loading, save: true });
    let AjaxRequest;
    if (id.current) {
      AjaxRequest = SaveEditDoc;
    } else {
      AjaxRequest = SaveDoc;
    }
    const res = await AjaxRequest(data);
    if (res.status === 200) {
      clearRouteBlocker();
      Toast.success('保存成功');
      const entryFromUrl = getSearchName('entry');
      if (entryFromUrl === 'draft') {
        // 草稿页跳转过来时，跳转回去
        return props.history.goBack();
      }
      props.history.replace('/official-doc/2');
    }
    setLoading({ ...loading, save: false });
  };

  return (
    <div className={styles.wrap}>
      <DocTotal
        {...props}
        handlePublish={handlePublish}
        handleSave={handleSave}
        loading={loading}
      />
      <Prompt message={(nextRoute) => setRouteBlocker(props.history, nextRoute)} />
    </div>
  );
};

export default DocCreatePage;